package comlookupd

import (
	"gitee.com/liukexing/mqbroker/core/server/pubsub"
	"gitee.com/liukexing/mqbroker/core/typedef"
	"sync"
	"time"
)

var (
	ComputeConfig sync.Map
)

func NewComputeHandle() *pubsub.ComputeServerHandle {
	return &pubsub.ComputeServerHandle{
		Config: &ComputeConfig,
		Request: map[string]typedef.CommonMsgConfig{
			"Update": typedef.CommonMsgConfig{
				Handle: UpdateCpt,
				Sub:    typedef.CommonMsgCheck{Receiver: Config.Info.ID},
			},
		},
	}
}

func UpdateCpt(data map[string]interface{}) (map[string]interface{}, error) {
	uptp := struct {
		Msgtype string
	}{}
	if err := typedef.Decode(data["data"], &uptp); err != nil {
		return nil, err
	}
	if uptp.Msgtype == "component" {
		info := struct {
			Msgtype string
			Key     string
			Data    typedef.ComInfo
		}{}
		if err := typedef.Decode(data["data"],&info); err != nil {
			return nil, err
		}
		cold, ok := ComMap.Load(info.Key)
		if !ok || cold.(typedef.ComInfo).LastUpdate.Sub(info.Data.LastUpdate) < 0 {
			ComMap.Store(info.Key, info.Data)
		}
	}
	if uptp.Msgtype == "config" {
		info := struct {
			Msgtype string
			Module  string
			Id      string
			Config  map[string]interface{}
		}{}
		if err := typedef.Decode(data["data"],&info); err != nil {
			return nil, err
		}
		if v, ok := ConfigMap.Load(info.Module); ok {
			conmap := v.(map[string]interface{})
			if c, es := conmap[info.Id]; es {
				oldup := c.(map[string]interface{})["LastUpdate"].(time.Time)
				newup := info.Config["LastUpdate"].(time.Time)
				if newup.Sub(oldup) > 0 {
					conmap[info.Id] = c
				}
			} else {
				conmap[info.Id] = c
			}
			ConfigMap.Store(info.Module, conmap)
		} else {
			ConfigMap.Store(info.Module, map[string]interface{}{
				info.Id: info.Config,
			})
		}

	}
	return nil, nil
}
